package core.transfer;

import java.io.File;
import java.io.IOException;
import java.util.Observable;

/**
 * Class ProtocolTranfer : Enables to copy a file from anywhere to anywhere
 * @project Universalcopy
 * @author Aurele TONNERRE, Romain Monnier
 */
public abstract class ProtocolTransfer extends Observable {

    static final int MAX_BUFFER_SIZE = 1024;
    public static final String STATUSES[] = {"Downloading", "Paused", "Complete", "Cancelled", "Error"};
    public static final int DOWNLOADING = 0;
    public static final int PAUSED = 1;
    public static final int COMPLETE = 2;
    public static final int CANCELLED = 3;
    public static final int ERROR = 4;

    String urlOrigin;
    static String urlDestination;
    long size;
    long downloaded;
    int status;
    static java.io.File file = null;

    public ProtocolTransfer(String urlOrigin, String urlDestination) {
        this.urlOrigin = urlOrigin;
        this.urlDestination = urlDestination;
        size = -1;
        status = DOWNLOADING;
    }
    
    public String completeUrl(String url) {
        if(Character.toString(url.charAt(url.length()-1)).compareTo("/") != 0)
            url = url+"/";
        return url;
    }

    public String getUrl() {
        return urlOrigin.toString();
    }

    public long getSize() {
        return size;
    }

    public float getProgress() {
        return (float)(downloaded / size * 100);
    }

    public int getStatus() {
        return status;
    }

    public void pause() {
        status = PAUSED;
        stateChanged();
    }

    public void resume() {
        status = DOWNLOADING;
        stateChanged();
        download();
    }

    public void cancel() {
        status = CANCELLED;
        stateChanged();
    }

    void error() {
        status = ERROR;
        stateChanged();
    }

    String getFileName(String url) {
        String fileName = url;
        return fileName.substring(fileName.lastIndexOf('/') + 1);
    }
    
    public long getFileSize(File file) {
        if (!file.exists() || !file.isFile()) {
            System.out.println("Le fichier n'existe pas");
            return -1;
        }
        return file.length();
    }
    
    void stateChanged() {
        setChanged();
        notifyObservers();
    }

    public abstract void download();
    
    public abstract void upload(File sourceFile, String destURL) throws IOException;
    
    public abstract void upload() throws IOException;
    
}